<template>
  <el-dialog
    :title="userId ? '编辑会员' : '新增会员'"
    :model-value="visible"
    width="600px"
    @update:model-value="$emit('update:visible', $event)"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="用户类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择用户类型">
          <el-option label="个人" value="personal" />
          <el-option label="机构" value="organization" />
        </el-select>
      </el-form-item>
      <el-form-item label="会员姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入会员姓名" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="身份证号" prop="id_card">
        <el-input v-model="form.id_card" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别">
          <el-option label="男" value="male" />
          <el-option label="女" value="female" />
          <el-option label="未知" value="unknown" />
        </el-select>
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          placeholder="请选择生日"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入地址" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item v-if="form.type === 'organization'" label="所属机构" prop="org_id">
        <el-select
          v-model="form.org_id"
          placeholder="请选择所属机构"
          filterable
          remote
          :remote-method="searchOrganizations"
          :loading="orgLoading"
        >
          <el-option
            v-for="item in orgOptions"
            :key="item.org_id"
            :label="item.company_name"
            :value="item.org_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-text="正常"
          inactive-text="禁用"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  userId: {
    type: [Number, String],
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 表单数据
const formRef = ref(null)
const loading = ref(false)
const form = reactive({
  type: 'personal',
  name: '',
  phone: '',
  id_card: '',
  gender: 'unknown',
  birthday: '',
  address: '',
  email: '',
  org_id: null,
  status: 1,
  remark: ''
})

// 机构选择相关
const orgLoading = ref(false)
const orgOptions = ref([])

// 表单验证规则
const rules = {
  type: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入会员姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  id_card: [
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  org_id: [
    { required: true, message: '请选择所属机构', trigger: 'change' }
  ]
}

// 监听用户ID变化
watch(() => props.userId, async (newVal) => {
  if (newVal) {
    await getUserInfo(newVal)
  } else {
    resetForm()
  }
})

// 获取用户信息
const getUserInfo = async (id) => {
  try {
    const res = await request.get(`/member/detail`, {
      params: { id }
    })
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取用户信息失败：', error)
  }
}

// 搜索机构
const searchOrganizations = async (query) => {
  if (query) {
    orgLoading.value = true
    try {
      const res = await request.get('/organization/list', {
        params: {
          keyword: query,
          page: 1,
          limit: 20
        }
      })
      orgOptions.value = res.data.list
    } catch (error) {
      console.error('搜索机构失败：', error)
    }
    orgLoading.value = false
  } else {
    orgOptions.value = []
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const url = props.userId ? '/member/update' : '/member/create'
        const data = { ...form }
        if (props.userId) {
          data.id = props.userId
        }
        await request.post(url, data)
        ElMessage.success(props.userId ? '更新成功' : '创建成功')
        emit('update:visible', false)
        emit('success')
      } catch (error) {
        console.error('保存失败：', error)
      }
      loading.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    type: 'personal',
    name: '',
    phone: '',
    id_card: '',
    gender: 'unknown',
    birthday: '',
    address: '',
    email: '',
    org_id: null,
    status: 1,
    remark: ''
  })
}
</script> 